package com.guavamail.smtp.command.impl;

import java.io.IOException;

import org.apache.mina.core.session.IoSession;

import com.guavamail.smtp.SMTPContext;
import com.guavamail.smtp.SessionStatus;
import com.guavamail.smtp.command.AbstractCommand;

public class MAIL extends AbstractCommand {
	public MAIL() {
		super("MAIL", "");
	}

	@Override
	public void execute(String commandString, IoSession ioSession, SMTPContext ctx) throws IOException {
		SessionStatus sessionStatus = ctx.getSessionStatus();
		if (!sessionStatus.getHasSeenHelo()) {
			sendResponse(ioSession, "503 Error: send HELO/EHLO first");
		} else if (sessionStatus.getHasSender()) {
			sendResponse(ioSession, "503 Sender already specified");
		} else {
			if (commandString.trim().equals("MAIL FROM:")) {
				sendResponse(ioSession, "501 Syntax: MAIL FROM: <address>");
				return;
			}

			String args = getArgPredicate(commandString);
			if (!args.toUpperCase().startsWith("FROM:")) {
				sendResponse(ioSession, "501 Syntax: MAIL FROM: <address>  Error in parameters: \""
						+ getArgPredicate(commandString) + "\"");
				return;
			}

			String emailAddress = extractEmailAddress(args, 5);
			if (isValidEmailAddress(emailAddress)) {
				sessionStatus.setFrom(emailAddress);
				sendResponse(ioSession, "250 Ok");
			} else {
				sendResponse(ioSession, "553 <" + emailAddress + "> Invalid email address");
			}
		}
	}
}
